// Project 5: Linked List
// 4.3.08

#include <stdlib.h>
#include <stdio.h>      
#include "lexer.h"

struct vm_State *new_vm () // creates new list
{
        struct vm_State *ll = (struct vm_State *) malloc (sizeof (struct vm_State));

		float r[10];
        ll->head = NULL;
        ll->tail = NULL;
		ll->regs = r;

        return ll;
}

struct node *new_node ( union value val, int type, int ln) // creates new node
{
        struct node *n = (struct node *) malloc (sizeof (struct node));

                // assign the valuues to the struct
                n->v = val;
                n->next = NULL;
                n->prev = NULL;
                n->linenum = ln;
                
        if (type == 1) // if integer
        {
                n->type = CHAR ;
        }
        
        if (type == 2) // if float
        {
                n->type = FLOAT ;       
        }
        
        if (type == 3) // if register
        {
                n->type = INTEGER ;
        }
        
        if (type == 4) // if opcode
        {
                n->type = OPCODE ;
        }
        
        return n;
}

void delete_node (struct node *n) // deletes a node
{
        free (n);
}

void delete_list (struct vm_State *ll) // deletes a list
{
        struct node *pos = ll->head;
        struct node *old;

        // free all the nodes in the list 
        while (pos != NULL) {
                old = pos;
                pos = pos->next;
                delete_node (old);
        }

        // free the list itself 
        free (ll);
}

void list_pushback (struct vm_State *ll, union value val, int type, int ln) // push new node to back of list
{
        if (ll->head == NULL) { 
                /* list is empty, so start at beginning */
                ll->head = ll->tail = new_node (val, type, ln);
        }
        else {
				struct node *pos = ll->tail;
                ll->tail = ll->tail->next = new_node (val, type, ln);
				ll->tail->prev = pos;
        }
}
